// base
import Taro, { Component } from '@tarojs/taro'
import { View, Button } from '@tarojs/components'
import { AtActionSheet } from 'taro-ui'
// redux
import { connect } from '@tarojs/redux'
import { DOREQUESTBASEINFORMATION } from './store/actions/pagebaseinformation'
import { UPDATEPAGEBASEINFORMATION } from './store/types/pagebaseinformation'
import { UPDATEPAGECHOOSEJOBINPUT } from '../../../pages/choose-job-input/store/types/pagechoosejobinput'
import { UPDATEUSERINFO } from '../../../store/types/userinfo'
import { UPDATEBASEUSERINFO } from '../../../store/types/baseuserinfo'
// less
import './index.less'

import pagebaseinformation from './store/reducers/pagebaseinformation'
import { getStore } from '../../../store/index'
import { injectReducer } from '../../../store/reducerUtils'
import MessageInputWrap from '../../../components/page-components/message-input-wrap'
import MessageSelectSingle from '../../../components/page-components/message-select-single'
import {
  navigateTo,
  redirectTo,
  navigateBack,
  switchTab
} from '../../../crossplatform/apiservice/navigate'
import pagejumplist from '../../../configuration/pagejumplist.json'
import ChooseGender from '../../../components/page-components/choose-gender'
import { formatDate } from '../../../util/lodashmin/formatDate'
import tool from '../../../util/tool'
import {
  getArchiveInfoRequest,
  getZhichuUserInfoByAuth,
  createAccountRequest,
  editUserInfoRequest,
  createAccountForBRequest,
  editAccountForBRequest,
  getZhichuUserInfoBByAuth
} from '../../../service/user-info-controller'
import { getZhichuBUserInfo } from '../../../store/actions/userinfo'
import { getUserArchiveInfoRequest } from '../../../service/user-archive-controller'
import { showToast } from '../../../crossplatform/apiservice/toast'
import { getStorageSync } from '../../../crossplatform/apiservice/storage'
import { getLocation } from '../../../crossplatform/apiservice/location'
import { positioning } from '../../../store/actions/landmark'
import { applyCompany } from '../../../service/org-company-controller'

const store = getStore()
injectReducer(store, {
  key: 'pagebaseinformation',
  reducer: pagebaseinformation
})

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGEBASEINFORMATION,
      payload: {
        ...payload
      }
    })
  },
  dorequest() {
    return new Promise(resolve => {
      let promise = DOREQUESTBASEINFORMATION()
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  updateJobInput(payload) {
    dispatch({
      type: UPDATEPAGECHOOSEJOBINPUT,
      payload: {
        ...payload
      }
    })
  },
  updateUserState(payload) {
    dispatch({
      type: UPDATEUSERINFO,
      payload: {
        ...payload
      }
    })
  },
  updateBaseUserState(payload) {
    dispatch({
      type: UPDATEBASEUSERINFO,
      payload: {
        ...payload
      }
    })
  },
  getCity(payload) {
    return new Promise(resolve => {
      let promise = positioning(payload)
      dispatch(promise)
      promise.payload.then(() => {
        resolve()
      })
    })
  }
})

@connect(
  ({ pagebaseinformation, pagechoosejobinput, userinfo, baseuserinfo, landmark }) => ({
    ...pagebaseinformation,
    ...userinfo,
    baseuserinfo,
    jobinput: pagechoosejobinput.inputData,
    landmarkName: landmark.landmarkName,
    landmarkLng: landmark.lng
  }),
  mapActiontoProps
)
class BaseInformation extends Component {
  config = {
    navigationBarTitleText: ''
  }

  constructor(props) {
    super(props)
    this.state = {
      modalVisible: false,
      submitData: {
        name: '',
        birthday: '',
        gender: 'male',
        mobile: ''
      },
      selectdatalist: {
        mode: 'date',
        name: '出生年份',
        start: '1900-01-01',
        end: formatDate('', 'YYYY-MM-DD'),
        type: 'birthday',
        fields: 'year',
        value: ''
      },
      jobHuntingModels: [],
      detailIn: '',
      educationExit: '',
      type: '' // 页面类型
    }
  }

  componentWillMount() {
    // onLoad
    const { type } = this.$router.params
    this.setState({
      type
    })
    const userinfo = getStorageSync('userinfo')
    this.props.updateUserState({
      ...userinfo
    })
  }

  componentDidMount() {
    // onready
  }

  componentDidShow() {
    // onshow
    const { landmarkName, landmarkLng } = this.props

    if (!landmarkName || !landmarkLng) {
      this.setLocation()
    }
    this.doOnShowInput && this.doOnShowInput()
    this.doOnShowInput = null

    const { detailIn, educationExit } = this.$router.params
    this.setState({
      detailIn, // 判断是否从岗位详情进入
      educationExit // 该用户是否有教育信息或者工作经验
    })

    this.queryWarp()
  }

  componentDidHide() {
    // onhide
    this.initState()
  }

  componentWillUnmount() {
    // onUnload
    this.initState()
  }

  queryWarp = () => {
    // 初始化数据
    const { userId } = this.props
    const { type } = this.state
    if (type) {
      userId &&
        getZhichuUserInfoBByAuth({ userId }).then(({ data = {} } = {}) => {
          const { entry, status } = data
          const yearPre18 = new Date().getFullYear() - 18
          if (status && entry) {
            const { selectdatalist } = this.state
            const {
              baseuserinfo: { userInfoB: baseUserInfoB }
            } = this.props
            const baseUserInfoBNew = { ...baseUserInfoB }
            let birthday =
              baseUserInfoBNew.birthday ||
              (entry.gmtBorth && entry.gmtBorth.substring(0, 4)) ||
              yearPre18

            this.props.updateBaseUserState({
              userInfoB: {
                ...baseUserInfoBNew,
                name: baseUserInfoBNew.name || entry.userName || '',
                birthday,
                mobile: entry.mobile || '',
                gender: baseUserInfoBNew.gender || entry.gender || '',
                position: baseUserInfoBNew.position || entry.postion,
                zhichuUserIdB: entry.id
              }
            })

            this.setState({
              selectdatalist: {
                ...selectdatalist,
                value: birthday
              }
            })
          } else {
          }
        })
    } else {
      userId &&
        Promise.all([
          this.getZhichuUserInfo({ userId }),
          getUserArchiveInfoRequest({ userId })
        ]).then(([data, { data: datain }]) => {
          if (Object.keys(data).length) {
            const { selectdatalist } = this.state
            const {
              baseuserinfo: { userInfoC: baseUserInfoC }
            } = this.props
            const baseUserInfoCNew = { ...baseUserInfoC }
            const {
              entry: { archive = {} }
            } = datain

            let userInfoC = data.userInfoC || {}
            let birthday =
              baseUserInfoCNew.birthday ||
              (userInfoC.gmtBirth && userInfoC.gmtBirth.substring(0, 4)) ||
              ''
            let jobHuntingModels = archive.jobHuntingModels
            this.props.updateBaseUserState({
              userInfoC: {
                ...baseUserInfoCNew,
                name: baseUserInfoCNew.name || userInfoC.userName || '',
                birthday,
                mobile: data.mobile || '',
                gender: baseUserInfoCNew.gender || userInfoC.gender,
                intro: archive.intro || '',
                archiveId: (archive.userArchiveModel && archive.userArchiveModel.id) || '',
                jobIntention: [...jobHuntingModels]
              }
            })

            this.setState({
              selectdatalist: {
                ...selectdatalist,
                value: birthday
              },
              jobHuntingModels
            })
          }
        })
    }
  }

  getZhichuUserInfo = ({ userId }) => {
    return new Promise(resolve => {
      getZhichuUserInfoByAuth({ userId }).then(({ data }) => {
        const { entry } = data
        if (entry && Object.keys(entry).length > 0) {
          resolve({
            userId,
            zhichuUserId: entry.id,
            mobile: entry.mobile,
            userInfoC: {
              mobile: entry.mobile,
              gender: entry.gender,
              gmtBirth: entry.gmtBorth ? entry.gmtBorth.substring(0, 4) : '',
              userAvator: entry.userAvator,
              userName: entry.userName
            }
          })
        } else {
          resolve({})
        }
      })
    })
  }

  doOnShowInput = null
  onInputChange = tool.throttle(({ type, value, name, componenttype, maxLength, tip }) => {
    // 编辑姓名
    this.doOnShowInput = () => {
      const { userInfoB, userInfoC } = this.props.baseuserinfo
      const { type: roleType } = this.state
      if (roleType) {
        let userInfoBNew = { ...userInfoB }
        userInfoBNew[type] = this.props.jobinput.value
        this.props.updateBaseUserState({
          userInfoB: userInfoBNew
        })
      } else {
        let userInfoCNew = { ...userInfoC }
        userInfoCNew[type] = this.props.jobinput.value
        this.props.updateBaseUserState({
          userInfoC: userInfoCNew
        })
      }
    }
    this.props.updateJobInput({
      inputData: { type, value, name, componenttype, maxLength, tip }
    })
    navigateTo({
      url: `${pagejumplist['choose-job-input'].path}`
    })
  })

  showGenderModal = () => {
    // 编辑性别
    this.setState({
      modalVisible: true
    })
  }

  onClickGender = gender => {
    // 选中性别
    const { type } = this.state
    if (type) {
      let userInfoB = { ...this.props.baseuserinfo.userInfoB }
      userInfoB.gender = gender
      this.props.updateBaseUserState({
        userInfoB
      })
    } else {
      let userInfoC = { ...this.props.baseuserinfo.userInfoC }
      userInfoC.gender = gender
      this.props.updateBaseUserState({
        userInfoC
      })
    }
  }

  initState = () => {
    // 初始化数据
    this.setState({
      modalVisible: false,
      jobHuntingModels: []
    })
  }

  onCancel = () => {
    // 隐藏弹框
    this.setState({
      modalVisible: false
    })
  }

  onBirthChange = tool.throttle(({ type, value }) => {
    const { selectdatalist, type: roleType } = this.state
    const {
      baseuserinfo: { userInfoC, userInfoB }
    } = this.props
    const dataSource = { ...selectdatalist }
    let subdata = {}
    subdata[type] = value

    dataSource.value = value
    this.setState({
      selectdatalist: dataSource
    })
    if (roleType) {
      this.props.updateBaseUserState({
        userInfoB: {
          ...userInfoB,
          ...subdata
        }
      })
    } else {
      this.props.updateBaseUserState({
        userInfoC: {
          ...userInfoC,
          ...subdata
        }
      })
    }
  })

  inputJumpTo = tool.throttle(() => {
    // 先获取存储的自我评价/ 再跳转页面
    this.saveUserInfo().then(() => {
      const { userId } = this.props
      getArchiveInfoRequest({ userId }).then(({ data }) => {
        const {
          entry: { archiveId }
        } = data
        const {
          baseuserinfo: { userInfoC }
        } = this.props
        const { intro } = userInfoC
        this.props.updateJobInput({
          inputData: {
            type: 'text',
            value: intro,
            name: '自我评价',
            componenttype: 'textarea',
            maxLength: 140,
            tip: '*充分展现自我优势，让更多企业发现你'
          }
        })

        this.props.updateBaseUserState({
          userInfoC: {
            ...userInfoC,
            archiveId
          }
        })

        navigateTo({
          url: `${pagejumplist['choose-job-input'].path}?self=1&archiveId=${archiveId}`
        })
      })
    })
  })

  onJobHunting = tool.throttle(() => {
    const {
      baseuserinfo: { userInfoC }
    } = this.props
    if (userInfoC.archiveId && userInfoC.intro) {
      navigateTo({
        url: `${pagejumplist['choose-work-nature'].path}?isBaseInfo=1`
      })
    } else {
      showToast({
        title: '请按顺序完成填写'
      })
    }
  })

  saveUserInfo = () => {
    return new Promise(resolve => {
      const { userId, zhichuUserId, mobile, role } = this.props
      // let year = new Date().getFullYear() - 18
      let {
        baseuserinfo: { userInfoC }
      } = this.props
      userInfoC.sex = userInfoC.gender
      // userInfoC.role = userInfoC.role == 'personal' ? 0 : 1
      const phone = mobile
      if (!phone) {
        showToast({
          title: '请填写手机号'
        })
        return
      }
      if (!userInfoC.name) {
        showToast({
          title: '请填写姓名'
        })
        return
      }
      const currentyear = new Date().getFullYear()
      if (!userInfoC.birthday || userInfoC.birthday > currentyear) {
        showToast({
          title: '出身年份不能为空且不能大于当前'
        })
        return
      }
      if (zhichuUserId) {
        const result = this.formatDataToSubmit({
          ...userInfoC,
          userId,
          phone,
          settype: 'edit',
          zhichuUserId
        })
        editUserInfoRequest({
          ...result
        }).then(() => {
          this.getZhichuUserInfo({ userId }).then(() => {
            resolve()
          })
        })
      } else {
        const result = this.formatDataToSubmit({ ...userInfoC, userId, phone })
        createAccountRequest({ ...result }).then(() => {
          this.getZhichuUserInfo({ userId }).then(() => {
            resolve()
          })
        })
      }
    })
  }

  saveUserInfoB = () => {
    // 存储B端个人信息
    return new Promise(resolve => {
      const {
        userId,
        baseuserinfo: { userInfoB },
        mobile
      } = this.props
      const yearPre18 = new Date().getFullYear() - 18
      const { zhichuUserIdB } = userInfoB
      let params = {
        mobile: userInfoB.mobile || mobile,
        position: userInfoB.position,
        userId: userInfoB.userId,
        userName: userInfoB.name,
        sex: userInfoB.gender,
        birthday: userInfoB.birthday || yearPre18
      }
      if (zhichuUserIdB) {
        params.id = zhichuUserIdB
        params.userId = userId
        editAccountForBRequest({ ...params }).then(({ data }) => {
          const { code, entry, message } = data
          if (code === 200) {
            // 提示后  返回上一页
            resolve(entry)
          } else {
            showToast({
              title: message || '请完善信息后提交'
            })
            resolve(false)
          }
        })
      } else {
        params.userId = userId
        createAccountForBRequest({ ...params }).then(({ data }) => {
          const { code, entry, message } = data
          if (code === 200) {
            resolve(entry)
          } else {
            showToast({
              title: message || '请完善信息后提交'
            })
            resolve(false)
          }
        })
      }
    })
  }

  formatDataToSubmit({ settype, birthday, name, phone, sex, userId, role = 0, zhichuUserId }) {
    const { userAvator } = this.props.userInfoC
    let result = {}
    if (settype == 'edit') {
      result.id = zhichuUserId
    } else {
      result.userId = userId
    }
    if (settype == 'edit') {
      result.gmtBirth = birthday + (birthday.length === 4 ? '-01-01 00:00:00' : '')
    } else {
      result.birth = birthday + (birthday.length === 4 ? '-01-01 00:00:00' : '')
    }
    result.mobile = phone
    result.sex = sex
    result.role = role
    result.userAvator = userAvator || ''
    result.userName = name
    return result
  }

  jumpTo = tool.throttle(type => {
    // 跳转到编写求职意向页面 0: 新增  1:编辑
    navigateTo({
      url: `${pagejumplist['edit-job-intention'].path}?isEdit=${type}`
    })
  })

  onConfirm = tool.throttle(() => {
    // 点击下一步
    const {
      baseuserinfo: { userInfoC, userInfoB },
      mobile,
      userId
    } = this.props
    const { detailIn, educationExit, type } = this.state
    if (type) {
      if (!userInfoB.name) {
        showToast({
          title: '请填写姓名'
        })
        return
      }
      if (!userInfoB.gender) {
        showToast({
          title: '请选择性别'
        })
        return
      }
      if (!userInfoB.birthday) {
        showToast({
          title: '请选择出生年份'
        })
        return
      }
      // 存储B端用户信息
      this.saveUserInfoB().then(entry => {
        if (entry) {
          // 直接跳转
          getZhichuBUserInfo({ userId })
          this.checkApply()
        }
      })
    } else {
      if (!userInfoC.name) {
        showToast({
          title: '请填写姓名'
        })
        return
      }
      if (!userInfoC.gender) {
        showToast({
          title: '请选择性别'
        })
        return
      }
      if (!userInfoC.birthday) {
        showToast({
          title: '请选择出生年份'
        })
        return
      }
      if (!userInfoC.intro) {
        showToast({
          title: '请填写自我评价'
        })
        return
      }
      if (!userInfoC.jobIntention.length) {
        showToast({
          title: '请填写求职意向'
        })
        return
      }
      // 存储用户信息
      this.saveUserInfo()
      if (educationExit) {
        navigateBack()
      } else {
        if (detailIn) {
          redirectTo({
            url: `${pagejumplist['education-information'].path}`
          })
        } else {
          navigateTo({
            url: `${pagejumplist['avator-page'].path}`
          })
        }
        this.props.updateUserState({
          userInfoC: {
            userName: userInfoC.name,
            gmtBirth: userInfoC.birthday,
            sex: userInfoC.gender,
            mobile: userInfoC.mobile || mobile
          },
          mobile: userInfoC.mobile || mobile
        })
      }
    }
  })

  onTap = () => {
    // 跳转到编写求职意向页面 0: 新增  1:编辑
    // navigateTo({
    //   url: `${pagejumplist['edit-job-intention'].path}?isEdit=${1}`
    // })
  }

  setLocation = () => {
    return new Promise(resolve => {
      if (!this.props.landmarkName) {
        getLocation()
          .then(res => {
            const { latitude, longitude } = res
            this.props.getCity({ lat: latitude, lng: longitude }).then(() => {
              resolve()
            })
          })
          .catch(() => {
            this.props.updateLandmark({
              landmarkName: '上海',
              cityId: 15
            })
            resolve()
          })
      } else {
        resolve()
      }
    })
  }

  checkApply = () => {
    const { role } = this.props
    if (role == 'personal') {
      // 调用接口 判断是否有B端身份  有: 跳转到我的页面 成功修改身份 无: 跳转到资料页/公司选择页
      const { userId } = this.props
      // 获取用户创建公司信息
      applyCompany({ userId }).then(({ data }) => {
        const { entry = {} } = data
        switch (entry.checkStatus) {
          case 0:
            switch (entry.type) {
              case 'company':
                // 如果用户有 则跳转创建公司页面
                navigateTo({
                  url: `${pagejumplist['create-new-cp'].path}?checkReason=${entry.checkReason}&tianYanChaId=${entry.tianYanChaId}&licenseUrl=${entry.licenseUrl}&name=${entry.companyName}&checkStatus=${entry.checkStatus}&companyId=${entry.companyId}`
                })
                break
              case 'operator':
                // 加入申请 申请拒绝
                redirectTo({
                  url: `${pagejumplist['join-new-cp'].path}?id=${entry && entry.companyId}&name=${
                    entry.companyName
                  }&status=${entry.checkStatus}`
                })
                break
              default:
                break
            }
            break
          case 1:
            // 加入申请审批通过(正常状态)  跳转到我的页面 成功修改身份
            let companyId = entry.companyId
            if (companyId) {
              this.props.updateUserState({
                role: 'company',
                companyId
              })
            } else {
              this.props.updateUserState({
                role: 'company'
              })
            }
            switchTab({
              url: pagejumplist['self-center'].path
            })
            break
          case 2:
            // 申请中
            switch (entry.type) {
              case 'company':
                // 如果用户有 则跳转创建公司页面
                navigateTo({
                  url: `${pagejumplist['create-new-cp'].path}?checkReason=${entry.checkReason}&tianYanChaId=${entry.tianYanChaId}&licenseUrl=${entry.licenseUrl}&name=${entry.companyName}&checkStatus=${entry.checkStatus}&companyId=${entry.companyId}`
                })
                break
              case 'operator':
                navigateTo({
                  url: `${pagejumplist['join-new-cp'].path}?id=${entry && entry.companyId}&name=${
                    entry.companyName
                  }&status=${entry.checkStatus}`
                })
                break
              default:
                break
            }
            break
          default:
            // 直接跳转
            redirectTo({
              url: pagejumplist['create-company'].path
            })
            break
        }
      })
    } else {
      this.props.updateUserState({
        role: 'personal'
      })
      let timer = setTimeout(() => {
        clearTimeout(timer)
        switchTab({
          url: pagejumplist['self-center'].path
        })
      }, 500)
    }
  }

  render() {
    const { modalVisible, selectdatalist, jobHuntingModels, educationExit, type } = this.state
    const {
      baseuserinfo: { userInfoC, userInfoB }
    } = this.props
    return (
      <View className="BaseInformation_id05182">
        <View className="top-title">
          <View className="title">
            <View className="title-text">基本信息</View>
          </View>
          <View className="desc">
            {type ? '*完善个人信息能更快的招到心仪的人才' : '*完善个人信息能更快的找到心仪的工作'}
          </View>
        </View>

        <View className="top-container">
          <MessageInputWrap
            maxLength="6"
            name="姓名"
            type="name"
            value={type ? userInfoB.name : userInfoC.name}
            tip="*请填写真实姓名"
            onChange={this.onInputChange}
          />

          <MessageSelectSingle
            name="性别"
            type="gender"
            value={
              type
                ? userInfoB.gender === 'female'
                  ? '女'
                  : '男'
                : userInfoC.gender === 'female'
                ? '女'
                : '男'
            }
            onChange={this.showGenderModal}
          />

          <MessageSelectSingle
            mode={selectdatalist.mode}
            name={selectdatalist.name}
            selectlist={selectdatalist.selectlist}
            type={selectdatalist.type}
            value={selectdatalist.value}
            onChange={this.onBirthChange}
            fields={selectdatalist.fields || ''}
          />

          {!type && (
            <MessageInputWrap
              maxLength="6"
              name="自我评价"
              value={userInfoC.intro}
              tip="*请填写自我评价"
              onChange={this.inputJumpTo}
              noBorder
            />
          )}
        </View>

        {type && (
          <View className="top-container">
            <MessageInputWrap
              maxLength="8"
              name="我的职务"
              type="position"
              value={userInfoB.position}
              tip="*公司组织架构的岗位名称"
              onChange={this.onInputChange}
              noBorder
            />
          </View>
        )}

        {!type && (
          <View className="top-container">
            <MessageInputWrap
              maxLength="6"
              name="求职意向"
              value=""
              onChange={this.onJobHunting}
              noBorder={!(jobHuntingModels && jobHuntingModels.length)}
              jobStatus={!!(jobHuntingModels && jobHuntingModels.length)}
            />

            {jobHuntingModels && jobHuntingModels.length && (
              <View className="job-hunting">
                {jobHuntingModels.map(item => {
                  let comprehensive = JSON.parse(item.comprehensive)
                  let workNature = comprehensive.workNature[0]
                  let workPlace = comprehensive.workPlace || []
                  return (
                    <View className="intention-card" onClick={this.onTap}>
                      <View className="title-view">
                        <View className="title">{workNature}</View>
                        {workNature == '兼职' ? (
                          <Image
                            className="card-left-img"
                            src="https://imagesize.hrwork.com/sp/files/f0f92fd2-5c5f-4702-88af-2c4bed62db22.png"
                          />
                        ) : workNature == '全职' ? (
                          <Image
                            className="card-left-img"
                            src="https://imagesize.hrwork.com/sp/files/6b18b1a7-0b04-4cea-85a3-0beb34cc0a89.png"
                          />
                        ) : (
                          <Image
                            className="card-left-img"
                            src="https://imagesize.hrwork.com/sp/files/6e26440e-b574-4830-be44-05a487fffe4d.png"
                          />
                        )}
                        <View className="area">{workPlace.join(' ')}</View>
                      </View>
                      <View className="tips">
                        {(comprehensive.workCategory ? comprehensive.workCategory : [])
                          .filter(e => e)
                          .map(e => (
                            <View className="tips-item" key={e}>
                              {e}
                            </View>
                          ))}
                      </View>
                    </View>
                  )
                })}
              </View>
            )}
          </View>
        )}

        <View className="btn">
          <Button onClick={this.onConfirm}>{`${educationExit ? '完成' : '下一步'}`}</Button>
        </View>

        <AtActionSheet isOpened={modalVisible} onClose={this.onCancel}>
          <ChooseGender
            title="选择性别"
            value={type ? userInfoB.gender : userInfoC.gender}
            onChange={this.onClickGender}
          />
        </AtActionSheet>
      </View>
    )
  }
}

export default BaseInformation
